#include "stdafx.h"
#include "GameScene.h"

#include "ModelNode.h"
#include "WorldData.h"
#include "NodeUtil.h"
#include "Brick.h"
#include "RenderingSystem.h"
#include "RenderingData.h"
#include "PhysicsSystem.h"
#include "Material.h"

#include "Mesh.h"

#include "Army.h"

using namespace mscene;

bool GameScene::init()
{
	bool result = true;

	//result &= initBall();

	Army * army = addNewArmy();

	mBricks.reserve(1000);

	for(uint br = 0; br < 9; br++)
	{
		Brick brick;
		brickInit(brick, PhysSys);

		XMFLOAT4 orient;
		XMStoreFloat4(&orient, XMQuaternionRotationRollPitchYaw(0, 0, 0));
		brickReset(brick, XMFLOAT3(br / 3 * 70, 20, br % 3 * 70), orient, XMFLOAT3(1,1,1));
		brick.Color = XMCOLOR4F_TO_3F(Color::RED);

		mBricks.push_back(brick);

		Brick & brickRef = mBricks[mBricks.size()-1];

		army->addUnit(brickRef, brickRef.Position, brickRef.Orientation);
	}

	army = addNewArmy();

	for(uint br = 0; br < 9; br++)
	{
		Brick brick;
		brickInit(brick, PhysSys);

		XMFLOAT4 orient;
		XMStoreFloat4(&orient, XMQuaternionRotationRollPitchYaw(0, 0, 0));
		brickReset(brick, XMFLOAT3(200 + br / 3 * 70, 20, 50 + br % 3 * 70), orient, XMFLOAT3(1,1,1));
		brick.Color = XMCOLOR4F_TO_3F(Color::GREEN);

		mBricks.push_back(brick);

		Brick & brickRef = mBricks[mBricks.size()-1];

		army->addUnit(brickRef, brickRef.Position, brickRef.Orientation);
	}

	return result;
}

GameScene::GameScene(mgfx::RenderingSystem & renderSys, mphys::PhysicsSystem & physSys)
	: Scene(renderSys, physSys), mNumArmies(0)
{

}

Army * GameScene::addNewArmy()
{
	assert(mNumArmies < MAX_PLAYERS);
	Army * army = new Army;
	mArmies[mNumArmies++] = army;
	army->mUnits.reserve(1000);
	return army;
}

void GameScene::gameUpdate( float dt )
{
	Scene::update(dt);

	for (uint i = 0; i < mNumArmies; i++)
	{
		mArmies[i]->update(dt);
	}

	updateBricksGfxData();
}

void GameScene::updateBricksGfxData()
{
	if(mBricks.size() > RenderSys.Data.Bricks.size())
		RenderSys.Data.Bricks.resize(mBricks.size());

	for(uint i = 0; i < mBricks.size(); i++)
	{
		mgfx::BrickGfxData & brickGfx = RenderSys.Data.Bricks[i];
		Brick & brick = mBricks[i];

		XMMATRIX world;
		world = XMMatrixScalingFromVector(XMLoadFloat3(&brick.Scale));
		world = XMMatrixMultiply(world, XMMatrixRotationQuaternion(XMLoadFloat4(&brick.Orientation)));
		world = XMMatrixMultiply(world, XMMatrixTranslationFromVector(XMLoadFloat3(&brick.Position)));

		XMStoreFloat4x4(&brickGfx.WorldMatrix, world);

		brickGfx.Position = brick.Position;
		brickGfx.BSphereRadius = brick.BSphereRadius;
		brickGfx.Color = brick.Color;
	}
}

void GameScene::teardown()
{
	for (uint i = 0; i < mNumArmies; i++)
	{
		delete mArmies[i];
	}

	mNumArmies = 0;
}
